package com.example.demo.service;

import com.example.demo.Exception.ProductAdminException;
import com.example.demo.dao.SupplierJPARepository;
import com.example.demo.entity.Supplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 *
 */
@Service
public class SupplierServer {

    @Autowired
    SupplierJPARepository supplierJPARepository;

    public Supplier addSuplier(Supplier supplier) throws ProductAdminException {
        if(supplier.getId() != null){
            if(supplierJPARepository.findById(supplier.getId()).isPresent()){
                throw new ProductAdminException("添加供应商失败，该供应商已经存在");
            }
        }
        return supplierJPARepository.saveAndFlush(supplier);
    }

    public void updateSuolier(long id,Supplier supplier) throws ProductAdminException {
        if(!supplierJPARepository.findById(id).isPresent()){
            throw new ProductAdminException("修改供应商失败：供应商"+id+"不存在");
        }
        supplierJPARepository.saveAndFlush(supplier);
    }

    public void deleteSupplier(long id) throws ProductAdminException {
        if(!supplierJPARepository.findById(id).isPresent()){
            throw new ProductAdminException("删除供应商失败：供应商"+id+"不存在");
        }
        supplierJPARepository.deleteById(id);
    }

    public Supplier getSupplier(long id){ return supplierJPARepository.getById(id);}

    public Page<Supplier> findSuppliers(String name, Pageable pageable){
        return supplierJPARepository.findByNameContaining(name,pageable);
    }

}
